#include "stm32f10x.h"                  // Device header
#include "Delay.h"

#define Trig  GPIO_Pin_2
#define Echo  GPIO_Pin_3

uint32_t Time = 0;
uint32_t Time_end = 0;

void GPIO_WriteTrig(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA, Trig, (BitAction)BitValue);
}

uint8_t GPIO_ReadEcho(void)
{
	return GPIO_ReadInputDataBit(GPIOA, Echo);
}

void Hcsro4_Init(void)
{	

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = Trig;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = Echo;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_WriteTrig(0);
	Delay_us(15);
}

void Hcsro4_TimeOut(void)
{
	uint32_t time = 100000;
	
	while (GPIO_ReadEcho() == 0)
	{
		time--;
		if(time == 0)
		{
			break;
		}
	}
}

uint16_t Hcsro4_Get_mm(void)
{
	uint32_t time1 = 1000000;
	uint32_t time2 = 1000000;
	
	uint32_t Distance = 0;
	uint32_t Distance_mm = 0;
	
	GPIO_WriteTrig(1);
	Delay_us(15);
	GPIO_WriteTrig(0);
	while (GPIO_ReadEcho() == 0)
	{
		time1--;
		if(time1 == 0)
		{
			break;
		}
	}
	Time = 0;
	while (GPIO_ReadEcho() == 1)
	{
		time2--;
		if(time2 == 0)
		{
			break;
		}
	}
	Time_end = Time;
	if (Time_end/100 < 38)
	{
		Distance = (Time_end * 346)/2;
		Distance_mm = Distance/100;
	}
	
	return Distance_mm;
}

float Hcsro4_Get_m(void)
{
	uint32_t Distance = 0;
	uint32_t Distance_mm = 0;
	float Distance_m = 0;
	
	GPIO_WriteTrig(1);
	Delay_us(15);
	GPIO_WriteTrig(0);
	while (GPIO_ReadEcho() == 0);
	Time = 0;
	while (GPIO_ReadEcho() == 1);
	Time_end = Time;
	if (Time_end/100 < 38)
	{
		Distance = (Time_end*346)/2;
		Distance_mm = Distance / 100;
		Distance_m = Distance_mm / 1000;
	}
	
	return Distance_m;
}


void TIM3_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET)
	{
		Time++;
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
	}
}

